<?php

namespace addons\store\server;

use data\service\BaseService;
use addons\store\model\VslStoreModel;
use addons\store\model\VslStoreJobsModel;
use addons\store\model\VslStoreAssistantModel;
use data\model\VslOrderModel;
use data\model\AlbumPictureModel;
use data\service\Order\Order as OrderBusiness;
use data\service\Address;
use addons\shop\service\Shop;
use data\service\Config as WebConfig;
use data\service\Upload\AliOss;
use data\model\UserModel;
use addons\store\model\VslStoreEvaluateModel;
use addons\store\model\VslStoreSetModel;
use \think\Session as Session;
use data\model\VslStoreGoodsModel as VslStoreGoodsModel;

/**
 * O2O数据处理
 * Class Good
 * @package addons\store\server
 */
class Store extends BaseService
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取门店列表
     * @param int|string $page_index
     * @param int|string $page_size
     * @param array $condition
     *
     * @return array $list
     */
    public function storeList($page_index = 1, $page_size = 0, array $condition = [])
    {
        $storeMdl = new VslStoreModel();
        $list = $storeMdl->pageQuery($page_index, $page_size, $condition, 'create_time desc', '*');
        return $list;
    }

    /**
     * 前台获取门店列表
     * @param int|string $page_index
     * @param int|string $page_size
     * @param array $condition
     *
     * @return array $list
     */
    public function storeListForFront($page_index = 1, $page_size = 0, array $condition = [], array $place = [])
    {
        $storeMdl = new VslStoreModel();
        $storeGoodsModel = new VslStoreGoodsModel();
        $list = $storeMdl->pageQuery($page_index, $page_size, $condition, 'create_time desc', '*');
        if ($list['data']) {
            //重新组装数组
            $newList = [];
            $address = new Address();
            if (getAddons('shop', $this->website_id)) {
                $shop = new Shop();
            }
            foreach ($list['data'] as $key => $val) {
                $newList[$key]['distance'] = $this->sphere_distance(['lat' => $val['lat'], 'lng' => $val['lng']], $place);
                $newList[$key]['store_id'] = $val['store_id'];
                $newList[$key]['shop_id'] = $val['shop_id'];
                $newList[$key]['website_id'] = $val['website_id'];
                $newList[$key]['store_name'] = $val['store_name'];
                $newList[$key]['store_tel'] = $val['store_tel'];
                $newList[$key]['province_name'] = $address->getProvinceName($val['province_id']);
                $newList[$key]['city_name'] = $address->getCityName($val['city_id']);
                $newList[$key]['dictrict_name'] = $address->getDistrictName($val['district_id']);
                // 查询图片表
                $goods_img = new AlbumPictureModel();
                $order = "instr('," . $val['img_id_array'] . ",',CONCAT(',',pic_id,','))"; // 根据 in里边的id 排序
                $goods_img_list = $goods_img->getQuery([
                    'pic_id' => [
                        "in",
                        $val['img_id_array']
                    ]
                ], 'pic_id,pic_cover', $order);
                if (trim($val['img_id_array']) != "") {
                    $img_temp_array = array();
                    $img_array = explode(",", $val['img_id_array']);
                    foreach ($img_array as $ki => $vi) {
                        if (!empty($goods_img_list)) {
                            foreach ($goods_img_list as $t => $m) {
                                if ($m["pic_id"] == $vi) {
                                    $img_temp_array[] = $m;
                                }
                            }
                        }
                    }
                }
                if ($img_temp_array) {
                    foreach ($img_temp_array as $kk => $vv) {
                        $img_temp_array[$kk]['pic_cover'] = __IMG($vv['pic_cover']);
                    }
                }
                $newList[$key]["img_temp_array"] = $img_temp_array;
                $newList[$key]['store_img'] = __IMG($img_temp_array[0]['pic_cover']);
                $newList[$key]['address'] = $val['address'];
                $newList[$key]['lat'] = $val['lat'];
                $newList[$key]['lng'] = $val['lng'];
                $newList[$key]['status'] = $val['status'];
                $newList[$key]['start_time'] = $val['start_time'];
                $newList[$key]['finish_time'] = $val['finish_time'];
                $newList[$key]['shop_name'] = '';
                $newList[$key]['score'] = $val['score'];
                if ($shop) {
                    $newList[$key]['shop_name'] = $shop->getShopInfo($val['shop_id'], 'shop_name')['shop_name'];
                }

                //查询每个门店的商品
                $where = [
                    'website_id' => $val['website_id'],
                    'shop_id' => $val['shop_id'],
                    'store_id' => $val['store_id'],
                    'status' => 1
                ];
                $newList[$key]['goods'] = $storeGoodsModel->viewPageQuery($storeGoodsModel, '1', '4', $where, 'price desc');
                //查询每个门店的商品图片
                foreach ($newList[$key]['goods'] as $k1 => $v1) {
                    $arr = $goods_img->Query(['pic_id' => $v1['picture']], 'pic_cover')[0];
                    $newList[$key]['goods'][$k1]['goods_img'] = $arr;
                    unset($arr);
                }
                //统计每个门店下所有商品的总销量
                $newList[$key]['total_sales'] = $storeGoodsModel->getSum($where, 'sales');
            }
            array_multisort(array_column($newList, 'distance'), SORT_ASC, $newList);
            $list['store_list'] = $newList;
        } else {
            $list['store_list'] = [];
        }
        unset($list['data']);
        return $list;
    }

    /**
     * 获取店员列表
     * @param int|string $page_index
     * @param int|string $page_size
     * @param array $condition
     *
     * @return array $list
     */
    public function assistantList($page_index = 1, $page_size = 0, array $condition = [])
    {
        $storeMdl = new VslStoreAssistantModel();
        $list = $storeMdl->getAssistantViewList($page_index, $page_size, $condition, 'vsa.create_time desc');
        return $list;
    }

    /**
     * 获取岗位列表
     * @param int|string $page_index
     * @param int|string $page_size
     * @param array $condition
     *
     * @return array $list
     */
    public function jobsList($page_index = 1, $page_size = 0, array $condition = [])
    {
        $storeMdl = new VslStoreJobsModel();
        $list = $storeMdl->pageQuery($page_index, $page_size, $condition, 'create_time desc', '*');
        return $list;
    }

    /*
     * 删除门店
     */

    public function deleteStore($store_id)
    {
        if (!$store_id) {
            return -1006;
        }

        $storeMdl = new VslStoreModel();
        $store = $storeMdl->getInfo(['store_id' => $store_id, 'website_id' => $this->website_id, 'shop_id' => $this->instance_id]);
        if (!$store) {
            return -10014;
        }
        $retval = $storeMdl->delData(['store_id' => $store_id, 'website_id' => $this->website_id, 'shop_id' => $this->instance_id]);
        return $retval;
    }

    /*
     * 删除店员
     */

    public function deleteAssistant($assistant_id)
    {
        if (!$assistant_id) {
            return -1006;
        }

        $assistantModel = new VslStoreAssistantModel();
        $assistant = $assistantModel->getInfo(['assistant_id' => $assistant_id, 'website_id' => $this->website_id, 'shop_id' => $this->instance_id]);
        if (!$assistant) {
            return -10014;
        }
        $retval = $assistantModel->delData(['assistant_id' => $assistant_id, 'website_id' => $this->website_id, 'shop_id' => $this->instance_id]);
        return $retval;
    }

    /*
     * 删除岗位
     */

    public function deleteJobs($jobs_id)
    {
        if (!$jobs_id) {
            return -1006;
        }

        $jobsModel = new VslStoreJobsModel();
        $store = $jobsModel->getInfo(['jobs_id' => $jobs_id, 'website_id' => $this->website_id, 'shop_id' => $this->instance_id]);
        if (!$store) {
            return -10014;
        }
        $retval = $jobsModel->delData(['jobs_id' => $jobs_id, 'website_id' => $this->website_id, 'shop_id' => $this->instance_id]);
        return $retval;
    }

    /**
     * 添加店员
     * @param array $input
     * @return int
     */
    public function addStore(array $input)
    {
        $storeModel = new VslStoreModel();
        $storeModel->startTrans();
        try {
            $data = array(
                'shop_id' => $this->instance_id,
                'website_id' => $this->website_id,
                'store_name' => $input['store_name'],
                'status' => $input['status'],
                'img_id_array' => $input['img_id_array'],
                'store_tel' => $input['store_tel'],
                'province_id' => $input['province_id'],
                'city_id' => $input['city_id'],
                'district_id' => $input['district_id'],
                'address' => $input['address'],
                'lat' => trim($input['lat']),
                'lng' => trim($input['lng']),
                'finish_time' => $input['finish_time'],
                'start_time' => $input['start_time'],
                'update_time' => time(),
                'create_time' => time()
            );
            $res = $storeModel->save($data);
            $storeModel->commit();
            return $res;
        } catch (\Exception $e) {
            $storeModel->rollback();
            return $e->getMessage();
        }
    }

    /**
     * 更新店员
     * @param array $input
     * @return int
     */
    public function updateStore(array $input)
    {
        $storeModel = new VslStoreModel();
        $storeModel->startTrans();
        $store_id = $input['store_id'];
        if (!$store_id) {
            return -1006;
        }
        try {
            $data = array(
                'shop_id' => $this->instance_id,
                'website_id' => $this->website_id,
                'store_name' => $input['store_name'],
                'status' => $input['status'],
                'img_id_array' => $input['img_id_array'],
                'store_tel' => $input['store_tel'],
                'province_id' => $input['province_id'],
                'city_id' => $input['city_id'],
                'district_id' => $input['district_id'],
                'address' => $input['address'],
                'lat' => trim($input['lat']),
                'lng' => trim($input['lng']),
                'finish_time' => $input['finish_time'],
                'start_time' => $input['start_time'],
                'update_time' => time()
            );
            $storeModel->save($data, ['store_id' => $store_id]);
            $storeModel->commit();
            return $store_id;
        } catch (\Exception $e) {
            $storeModel->rollback();
            return $e->getMessage();
        }
    }

    /**
     * 添加店员
     * @param array $input
     * @return int
     */
    public function addAssistant(array $input)
    {
        $assistantModel = new VslStoreAssistantModel();
        $checkAssistant = $assistantModel->getInfo(['assistant_tel' => $input['assistant_tel'], 'website_id' => $this->website_id], 'assistant_id');
        if ($checkAssistant) {
            return -8005;
        }
        $assistantModel->startTrans();
        try {
            $data = array(
                'shop_id' => $this->instance_id,
                'website_id' => $this->website_id,
                'store_id' => $input['store_id'],
                'jobs_id' => $input['jobs_id'],
                'assistant_name' => $input['assistant_name'],
                'status' => $input['status'],
                'assistant_tel' => $input['assistant_tel'],
                'password' => md5($input['password']),
                'update_time' => time(),
                'create_time' => time()
            );
            $res = $assistantModel->save($data);
            $assistantModel->commit();
            return $res;
        } catch (\Exception $e) {
            $assistantModel->rollback();
            return $e->getMessage();
        }
    }

    /**
     * 更新店员
     * @param array $input
     * @return int
     */
    public function updateAssistant(array $input)
    {
        $assistantModel = new VslStoreAssistantModel();
        $checkAssistant = $assistantModel->getInfo(['assistant_tel' => $input['assistant_tel'], 'website_id' => $this->website_id, 'assistant_id' => ['<>', $input['assistant_id']]], 'assistant_id');
        if ($checkAssistant) {
            return -8005;
        }
        $assistantModel->startTrans();
        $assistant_id = $input['assistant_id'];
        if (!$assistant_id) {
            return -1006;
        }
        try {
            $data = array(
                'shop_id' => $this->instance_id,
                'website_id' => $this->website_id,
                'store_id' => $input['store_id'],
                'jobs_id' => $input['jobs_id'],
                'assistant_name' => $input['assistant_name'],
                'status' => $input['status'],
                'assistant_tel' => $input['assistant_tel'],
                //'password' => md5($input['password']),
                'update_time' => time()
            );
            $assistantModel->save($data, ['assistant_id' => $assistant_id]);
            $assistantModel->commit();
            return 1;
        } catch (\Exception $e) {
            $assistantModel->rollback();
            return $e->getMessage();
        }
    }

    /**
     * 添加岗位
     * @param array $input
     * @return int
     */
    public function addJobs(array $input)
    {
        $jobsModel = new VslStoreJobsModel();
        $jobsModel->startTrans();
        try {
            $data = array(
                'shop_id' => $this->instance_id,
                'website_id' => $this->website_id,
                'jobs_name' => $input['jobs_name'],
                'module_id_array' => $input['module_id_array'],
                'update_time' => time(),
                'create_time' => time()
            );
            $res = $jobsModel->save($data);
            $jobsModel->commit();
            return $res;
        } catch (\Exception $e) {
            $jobsModel->rollback();
            return $e->getMessage();
        }
    }

    /**
     * 编辑岗位
     * @param array $input
     * @return int
     */
    public function updateJobs(array $input)
    {
        $jobsModel = new VslStoreJobsModel();
        $jobs_id = $input['jobs_id'];
        if (!$jobs_id) {
            return -1006;
        }
        $jobsModel->startTrans();
        try {
            $data = array(
                'shop_id' => $this->instance_id,
                'website_id' => $this->website_id,
                'jobs_name' => $input['jobs_name'],
                'module_id_array' => $input['module_id_array'],
                'update_time' => time(),
                'create_time' => time()
            );
            $jobsModel->save($data, ['jobs_id' => $jobs_id]);
            $jobsModel->commit();
            return $jobs_id;
        } catch (\Exception $e) {
            $jobsModel->rollback();
            return $e->getMessage();
        }
    }

    /**
     * 获取门店详情
     * @param int $store_id
     * @return array $info
     */
    public function storeDetail($store_id)
    {
        if (!$store_id) {
            return false;
        }
        $storeModel = new VslStoreModel();
        $info = $storeModel->get($store_id);
        // 查询图片表
        $goods_img = new AlbumPictureModel();
        $order = "instr('," . $info['img_id_array'] . ",',CONCAT(',',pic_id,','))"; // 根据 in里边的id 排序
        $goods_img_list = $goods_img->getQuery([
            'pic_id' => [
                "in",
                $info['img_id_array']
            ]
        ], 'pic_id,pic_cover', $order);
        if (trim($info['img_id_array']) != "") {
            $img_temp_array = array();
            $img_array = explode(",", $info['img_id_array']);
            foreach ($img_array as $ki => $vi) {
                if (!empty($goods_img_list)) {
                    foreach ($goods_img_list as $t => $m) {
                        if ($m["pic_id"] == $vi) {
                            $img_temp_array[] = $m;
                        }
                    }
                }
            }
        }
        $info["img_temp_array"] = $img_temp_array;
        $address = new Address();
        $address_name['province_name'] = $address->getProvinceName($info['province_id']);
        $address_name['city_name'] = $address->getCityName($info['city_id']);
        $address_name['dictrict_name'] = $address->getDistrictName($info['district_id']);
        $info["detailed_address"] = $address_name['province_name'] . $address_name['city_name'] . $address_name['dictrict_name'] . $info['address'];
        $shop_name = '自营店';
        if (getAddons('shop', $this->website_id) && $info['shop_id']) {
            $shop = new Shop();
            $shop_info = $shop->getShopInfo($info['shop_id'], 'shop_name');
            $shop_name = $shop_info['shop_name'] ?: '自营店';
        }
        $info['shop_name'] = $shop_name;
        return $info;
    }

    /**
     * 获取店员详情
     * @param int $assistant_id
     * @return array $info
     */
    public function assistantDetail($assistant_id, $store_id = 0)
    {
        if (!$assistant_id) {
            return [];
        }
        $assistantModel = new VslStoreAssistantModel();
        $info = $assistantModel->getInfo(['assistant_id' => $assistant_id], 'assistant_id,store_id,jobs_id,shop_id,website_id,assistant_name,assistant_tel,status,assistant_headimg');
        $info['store_info'] = $this->storeDetail($store_id);
        $info['jobs_info'] = $this->jobDetail($info['jobs_id']);
        $info['jobs_info']['operation'] = $this->getModule($info['jobs_info']['module_id_array']);
        $shop_name = '自营店';
        if (getAddons('shop', $this->website_id) && $info['shop_id']) {
            $shop = new Shop();
            $shop_info = $shop->getShopInfo($info['shop_id'], 'shop_name');
            $shop_name = $shop_info['shop_name'] ?: '自营店';
        }
        $info['shop_name'] = $shop_name;
        return $info;
    }

    /**
     * 获取店员详情
     * @param array $condition
     * @return array $info
     */
    public function getAssistantInfo($condition = array())
    {
        if (!$condition) {
            return [];
        }
        $assistantModel = new VslStoreAssistantModel();
        $info = $assistantModel->getInfo($condition, 'assistant_id,store_id,jobs_id,shop_id,website_id,assistant_name,assistant_tel,status,assistant_headimg,wx_openid');
        return $info;
    }

    /**
     * 获取岗位详情
     * @param int $jobs_id
     * @return array $info
     */
    public function jobDetail($jobs_id)
    {
        if (!$jobs_id) {
            return [];
        }
        $assistantModel = new VslStoreJobsModel();
        $info = $assistantModel->get($jobs_id);
        return $info;
    }

    /*
     * 根据经纬度计算两点之间的距离
     */

    public function sphere_distance($placeA = array(), $placeB = array(), $radius = 6378.135)
    {
        $rad = doubleval(M_PI / 180.0);
        if (!$placeB) {
            $placeB = $this->getCurrentLat();
        }
        $lat1 = doubleval($placeA['lat']) * $rad;
        $lon1 = doubleval($placeA['lng']) * $rad;
        $lat2 = doubleval($placeB['lat']) * $rad;
        $lon2 = doubleval($placeB['lng']) * $rad;
        $theta = $lon2 - $lon1;
        $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));
        if ($dist < 0) {
            $dist += M_PI;
        }
        // 单位为 千米
        return $dist = round($dist * $radius, 2);
    }

    /*
     * 根据ip获取当前经纬度
     */

    public function getCurrentLat()
    {
        $getIp = $_SERVER["REMOTE_ADDR"];
        $content = file_get_contents("http://api.map.baidu.com/location/ip?ak=t16W0CsDyfV8QjlSgS17lgsI");
        $json = json_decode($content);
        $data = '';
        $data['lng'] = $json->{'content'}->{'point'}->{'x'}; //按层级关系提取经度数据
        $data['lat'] = $json->{'content'}->{'point'}->{'y'}; //按层级关系提取纬度数据
        $data['address'] = $json->{'content'}->{'address'};
        return $data;
    }

    /**
     * 生成核销码
     *
     *
     * @return string $billno
     */
    public function createVerificationCode()
    {
        $billno = 'A' . mt_rand(1000000000, 10000000000) . mt_rand(0, 9);
        while (1) {
            $order_model = new VslOrderModel();
            $count = $order_model->getCount(['order_no' => $billno]);
            if ($count <= 0) {
                break;
            }
            $billno = 'A' . mt_rand(1000000000, 10000000000) . mt_rand(0, 9);
        }
        return $billno;
    }

    /**
     * 订单提货(non-PHPdoc)
     *
     */
    public function pickupOrder($order_id)
    {
        $checkOrder = $this->checkOrderCanPick($order_id);//检查订单是否可以提货
        if ($checkOrder < 0) {
            return $checkOrder;
        }
        $order = new OrderBusiness();
        $retval = $order->pickupOrder($order_id);
        if ($retval) {
            $this->deleteVerCode($order_id);
        }
        return $retval;
    }

    /*
     * 核销订单核销二维码保存
     */

    public function orderVerCodeSet($verification_qrcode = '', $order_id = 0)
    {
        if (!$verification_qrcode || !$order_id) {
            return false;
        }
        $data = array(
            'verification_qrcode' => $verification_qrcode
        );
        $orderModel = new VslOrderModel();
        $result = $orderModel->save($data, [
            'order_id' => $order_id
        ]);
        return $result;
    }

    /*
     * 查询店铺是否拥有门店,作为是否o2o的依据
     */

    public function checkHasStoreForShop($shop_id = 0)
    {
        $storeModel = new VslStoreModel();
        $count = $storeModel->getCount(['shop_id' => $shop_id, 'website_id' => $this->website_id]);
        if (!$count) {
            return 0;
        }
        return 1;
    }

    /*
     * 核销完成删除门店订单核销码
     */

    public function deleteVerCode($order_id = 0)
    {
        if (!$order_id) {
            return false;
        }
        $orderModel = new VslOrderModel();
        $order = $orderModel->getInfo(['order_id' => $order_id], 'verification_qrcode');
        if (!$order['verification_qrcode']) {
            return false;
        }
        $qrcode = $order['verification_qrcode'];
        if (!strstr($qrcode, 'http')) {
            @unlink($qrcode);
        } elseif (@fopen($qrcode, 'r')) {
            $config = new WebConfig();
            $upload_type = $config->getUploadType();
            if ($upload_type == 2) {
                $alioss = new AliOss();
                $data = $alioss->deleteAliOss($qrcode);
                return $data;
            } else {
                return false;
            }
        }
        return true;
    }

    /*
     * 获取店员操作台权限
     */

    public function getModule($module_id_array = '')
    {
        if (!$module_id_array) {
            return [];
        }
        $module = explode(',', $module_id_array);
        $newList = [];
        foreach ($module as $key => $val) {
            if (!$val) {
                continue;
            }
            $newList[$key]['module_id'] = $val;
            $newList[$key]['module_name'] = $this->getModuleName($val);
        }
        return $newList;
    }

    /*
     * 获取操作台权限名称
     */

    public function getModuleName($module_id = 0)
    {
        if (!$module_id) {
            return '';
        }
        $module_name_arr = [
            1 => '扫码核销',
            2 => '卡券核销',
            3 => '礼品核销',
            4 => '门店订单',
            5 => '销售统计',
            6 => '店员管理'
        ];
        return $module_name_arr[$module_id];
    }

    public function getAssistantId($user_token = '')
    {
        $user_token = $user_token ?: $_SERVER['HTTP_USER_TOKEN'];
        $uid = Session::get($user_token);
        $base = new BaseService();
        $model = $base->getRequestModel();
        if ($uid == Session::get($model . 'assistant_id') && !is_null($uid)) {
            return $uid;
        } else {
            $assistantModel = new VslStoreAssistantModel();
            $user_info = $assistantModel::get(['user_token' => $user_token]);
            if ($user_info && $user_info['status'] == 1) {
                Session::set($model . 'assistant_id', $user_info['assistant_id']);
                Session::set(md5($user_info['assistant_id']), $user_info['assistant_id']);
                Session::set($model . 'instance_id', $user_info['shop_id']);
                Session::set($model . 'website_id', $user_info['website_id']);
                Session::set($model . 'store_id', $user_info['store_id']);
                $assistantModel->save(['login_num' => $user_info['login_num'] + 1], ['user_token' => $user_token]);
                return $user_info['assistant_id'];
            }
            return false;
        }
    }

    /**
     * 店员登录
     *
     * @param unknown $user_name
     * @param unknown $password
     */
    public function login($assistant_tel, $password = '')
    {
        $this->Logout();
        $condition = [
            'assistant_tel' => $assistant_tel,
            'website_id' => $this->website_id,
        ];
        if ($password) {
            $condition['password'] = md5($password);
        }
        $assistantModel = new VslStoreAssistantModel();
        $assistantInfo = $assistantModel->getInfo($condition, $field = 'assistant_id,status,assistant_name,assistant_headimg,shop_id,website_id,store_id');
        if (!empty($assistantInfo)) {
            if ($assistantInfo['status'] == 0) {
                return USER_LOCK;
            } else {
                $this->initLoginInfo($assistantInfo);
                //登录成功后增加用户的登录次数
                $set_inc_condition['assistant_id'] = $assistantInfo['assistant_id'];
                $assistantModel->save(['login_num' => $assistantInfo['login_num'] + 1, 'user_token' => md5($assistantInfo['assistant_id'])], $set_inc_condition);
                return $assistantInfo;
            }
        } else {
            return USER_ERROR;
        }
    }

    /**
     * 店员user_token登录
     *
     * @param unknown $user_name
     * @param unknown $password
     */
    public function loginByUserToken($user_token)
    {
        $this->Logout();
        $condition = [
            'user_token' => $user_token,
            'website_id' => $this->website_id,
        ];
        $assistantModel = new VslStoreAssistantModel();
        $assistantInfo = $assistantModel->getInfo($condition, $field = 'assistant_id,status,assistant_name,assistant_headimg,shop_id,website_id,store_id');
        if (!empty($assistantInfo)) {
            if ($assistantInfo['status'] == 0) {
                return USER_LOCK;
            } else {
                $this->initLoginInfo($assistantInfo);
                //登录成功后增加用户的登录次数
                $set_inc_condition['assistant_id'] = $assistantInfo['assistant_id'];
                $assistantModel->save(['login_num' => $assistantInfo['login_num'] + 1, 'user_token' => md5($assistantInfo['assistant_id'])], $set_inc_condition);
                return $assistantInfo;
            }
        } else {
            return USER_NBUND;
        }
    }

    /**
     * 店员user_token登录
     *
     * @param unknown $user_name
     * @param unknown $password
     */
    public function loginByOpenid($open_id)
    {
        $this->Logout();
        $condition = [
            'wx_openid' => $open_id,
            'website_id' => $this->website_id,
        ];
        $assistantModel = new VslStoreAssistantModel();
        $assistantInfo = $assistantModel->getInfo($condition, $field = 'assistant_id,status,assistant_name,assistant_headimg,shop_id,website_id,store_id');
        if (!empty($assistantInfo)) {
            if ($assistantInfo['status'] == 0) {
                return USER_LOCK;
            } else {
                $this->initLoginInfo($assistantInfo);
                //登录成功后增加用户的登录次数
                $set_inc_condition['assistant_id'] = $assistantInfo['assistant_id'];
                $assistantModel->save(['login_num' => $assistantInfo['login_num'] + 1, 'user_token' => md5($assistantInfo['assistant_id'])], $set_inc_condition);
                return $assistantInfo;
            }
        } else {
            return USER_NBUND;
        }
    }

    /**
     * 店员登录之后初始化数据
     * @param unknown $user_info
     */
    public function initLoginInfo($user_info)
    {
        $base = new BaseService();
        $model = $base->getRequestModel();
        Session::set($model . 'assistant_id', $user_info['assistant_id']);
        Session::set(md5($user_info['assistant_id']), $user_info['assistant_id']);
        Session::set($model . 'instance_id', $user_info['shop_id']);
        Session::set($model . 'website_id', $user_info['website_id']);
        return true;
    }

    /*
     * 更新店员部分内容
     */

    public function updateAssistantFiled(array $data, $condition, $only_update_one_row = true)
    {
        $assistantModel = new VslStoreAssistantModel();
        //只允许修改修改一条记录
        if ($only_update_one_row && ($assistantModel->getCount($condition) != 1)) {
            return 0;
        }
        return $assistantModel->save($data, $condition);
    }

    /**
     * 店员退出
     */
    public function Logout()
    {
        Session::destroy();
    }

    /**
     * 门店评价-添加
     */
    public function addStoreEvaluate($data)
    {
        $storeEvaluateModel = new VslStoreEvaluateModel();
        $res = $storeEvaluateModel->save($data);
        $storeModel = new VslStoreModel();
        $storeEvaluate = $this->getStoreEvaluate($data['store_id']);
        $storeData['score'] = number_format(($storeEvaluate['store_service'] * $storeEvaluate['count'] + $data['store_service']) / ($storeEvaluate['count'] + 1), 1);
        $storeModel->save($storeData, ['store_id' => $data['store_id'], 'shop_id' => $data['shop_id'], 'website_id' => $data['website_id']]);
        return $res;
    }

    /*
     * 获取门店评价
     */

    public function getStoreEvaluate($store_id = 0)
    {
        $storeEvaluateModel = new VslStoreEvaluateModel();
        $count = $storeEvaluateModel->getCount(['store_id' => $store_id, 'website_id' => $this->website_id]);
        $evaluateData = ['store_service' => 0];
        if (!$count) {
            return $evaluateData;
        }
        $evaluateData['count'] = $count;
        $evaluateData['store_service'] = number_format($storeEvaluateModel->getSum(['store_id' => $store_id, 'website_id' => $this->website_id], 'store_service') / $count, 1);
        return $evaluateData;
    }

    /*
     * 根据店员id获取所能管理的门店列表
     */

    public function storeListByAssistantId($assistant_id = 0, $page_index = 1, $page_size = 0)
    {
        if (!$assistant_id) {
            return false;
        }
        $assistantModel = new VslStoreAssistantModel();

        $store_ids = $assistantModel->getInfo(['assistant_id' => $assistant_id], 'store_id');
        if (!$store_ids) {
            return false;
        }
        $storeList = $this->storeList($page_index, $page_size, ['store_id' => ['in', $store_ids['store_id']]]);
        foreach ($storeList['data'] as $key => $val) {
            // 查询图片表
            $goods_img = new AlbumPictureModel();
            $order = "instr('," . $val['img_id_array'] . ",',CONCAT(',',pic_id,','))"; // 根据 in里边的id 排序
            $goods_img_list = $goods_img->getQuery([
                'pic_id' => [
                    "in",
                    $val['img_id_array']
                ]
            ], 'pic_id,pic_cover', $order);
            if (trim($val['img_id_array']) != "") {
                $img_temp_array = array();
                $img_array = explode(",", $val['img_id_array']);
                foreach ($img_array as $ki => $vi) {
                    if (!empty($goods_img_list)) {
                        foreach ($goods_img_list as $t => $m) {
                            if ($m["pic_id"] == $vi) {
                                $img_temp_array[] = $m;
                            }
                        }
                    }
                }
            }
            if ($img_temp_array) {
                foreach ($img_temp_array as $kk => $vv) {
                    $img_temp_array[$kk]['pic_cover'] = __IMG($vv['pic_cover']);
                }
            }
            $storeList['data'][$key]['store_img'] = __IMG($img_temp_array[0]['pic_cover']);
            $storeList['data'][$key]['shop_name'] = '自营店';
            if (getAddons('shop', $this->website_id) && $val['shop_id']) {
                $shop = new Shop();
                $shop_info = $shop->getShopInfo($val['shop_id'], 'shop_name');
                $storeList['data'][$key]['shop_name'] = $shop_info['shop_name'] ?: '自营店';

            }
        }
        return $storeList;
    }

    /*
     * 检查选择的门店是否属于当前店员
     */

    public function checkStore($store_id = 0, $assistant_id = 0)
    {
        if (!$store_id || !$assistant_id) {
            return false;
        }
        $assistantModel = new VslStoreAssistantModel();
        $assInfo = $assistantModel->getInfo(['assistant_id' => $assistant_id], 'store_id');
        $store_ids = explode(',', $assInfo['store_id']);
        if (!in_array($store_id, $store_ids)) {
            return false;
        }
        return true;
    }

    /*
     * 启用店员
     */

    public function enableAssistant($assistant_id = 0)
    {
        if (!$assistant_id) {
            return LACK_OF_PARAMETER;
        }
        $assistantModel = new VslStoreAssistantModel();
        $assInfo = $assistantModel->getInfo(['assistant_id' => $assistant_id], 'assistant_tel');
        if (!$assInfo) {
            return 0;
        }
        $checkAss = $assistantModel->getInfo(['assistant_tel' => $assInfo['assistant_tel'], 'assistant_id' => ['<>', $assistant_id], 'website_id' => $this->website_id, 'status' => 1], 'assistant_id');
        if ($checkAss) {
            return ASSIS_UNOPEN;
        }
        $result = $assistantModel->save(['status' => 1, 'update_time' => time()], ['assistant_id' => $assistant_id]);
        if (!$result) {
            return 0;
        }
        return $result;
    }

    /*
     * 禁用店员
     */

    public function unableAssistant($assistant_id = 0)
    {
        if (!$assistant_id) {
            return LACK_OF_PARAMETER;
        }
        $assistantModel = new VslStoreAssistantModel();
        $assInfo = $assistantModel->getInfo(['assistant_id' => $assistant_id], 'assistant_tel');
        if (!$assInfo) {
            return 0;
        }
        $result = $assistantModel->save(['status' => 0, 'update_time' => time()], ['assistant_id' => $assistant_id]);
        if (!$result) {
            return 0;
        }
        return $result;
    }

    /*
     * 微信第三方登录(non-PHPdoc)
     * @see \data\api\IMember::wchatLogin()
     */
    public function wchatLogin($openid)
    {
        $this->Logout();
        $condition = array(
            'wx_openid' => $openid,
            'website_id' => $this->website_id
        );
        $assistantModel = new VslStoreAssistantModel();
        $user_info = $assistantModel->getInfo($condition, $field = 'assistant_id,assistant_name,shop_id,website_id,status');
        if (!empty($user_info)) {
            if ($user_info['status'] == 0) {
                return USER_LOCK;
            } else {
                $this->initLoginInfo($user_info);
                return $user_info['assistant_id'];
            }
        } else {
            return USER_NBUND;
        }
        // TODO Auto-generated method stub
    }

    /*
     * 获取门店配置
     */
    public function getStoreSet($shop_id = 0)
    {
        if (!$shop_id) {
            $shop_id = $this->instance_id;
        }
        $storeSetModel = new VslStoreSetModel();
        $info = $storeSetModel->getInfo([
            'shop_id' => $shop_id,
            'website_id' => $this->website_id
        ], '*');
        if (empty($info['value'])) {
            $storeSet = array(
                'is_use' => 0
            );
        } else {
            $info['value'] = json_decode(str_replace("&quot;", "\"", $info['value']), true);
            $storeSet = $info['value'];
        }
        return $storeSet;
    }

    /*
     * 设置门店配置
     */
    public function storeSet($data = array())
    {
        $storeSetModel = new VslStoreSetModel();
        if (is_array($data)) {
            $value = json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        $info = $storeSetModel->getInfo([
            'shop_id' => $this->instance_id,
            'website_id' => $this->website_id
        ], 'id');
        $saveData = array(
            'value' => $value
        );
        if ($info) {
            $saveData['modify_time'] = time();
            $result = $storeSetModel->save($saveData, ['id' => $info['id']]);
        } else {
            $saveData['create_time'] = time();
            $saveData['shop_id'] = $this->instance_id;
            $saveData['website_id'] = $this->website_id;
            $result = $storeSetModel->save($saveData);
        }
        return $result;
    }

    /*
     * 检查订单是否可以提货
     */
    public function checkOrderCanPick($order_id = 0)
    {
        if (!$order_id) {
            return -1;
        }
        $orderModel = new VslOrderModel();
        $orderInfo = $orderModel->getInfo(['order_id' => $order_id]);
        if (!$orderInfo) {
            return -10005;
        }
        if ($orderInfo['order_type'] == 5 && getAddons('groupshopping', $orderInfo['website_id'], $orderInfo['shop_id'])) {
            if (!$orderInfo['group_record_id'] || !$orderInfo['group_id']) {
                return -10005;
            }
            $groupShopping = new \addons\groupshopping\server\GroupShopping();
            $groupRecordDetail = $groupShopping->groupRecordDetail($orderInfo['group_record_id']);
            if ($groupRecordDetail['status'] != 1) {
                return -10018;
            }
        }
        return 1;
    }


}
